package com.yonyou.pmclouds.workstartreport.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.consts.CheckItemConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.billview.entity.BillViewQueryVO;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.rmiitf.EnterpriseQuery;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemBillStatusConst;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workflow.service.rmiitf.IWorkFlowService;
import com.yonyou.pmclouds.workquality.entity.WorkqualityDetailVO;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkQuaDetailQuery;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityQueryService;
import com.yonyou.pmclouds.workstartreport.entity.WorkStartCheckVO;
import com.yonyou.pmclouds.workstartreport.entity.WorkStartVO;
import com.yonyou.pmclouds.workstartreport.mapper.WorkStartCheckMapper;
import com.yonyou.pmclouds.workstartreport.mapper.WorkStartMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 开工报告查询接口
 */
@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = com.yonyou.pmclouds.workstartreport.rmiitf.WorkStartQuery.class)
public class WorkStartQueryImpl implements com.yonyou.pmclouds.workstartreport.rmiitf.WorkStartQuery , IPageQuerySerivce<WorkStartVO> {
    @Autowired
    private WorkStartMapper workStartMapper;
    @Autowired
    private WorkStartCheckMapper checkMapper;
    @Autowired
    private PictureRemoteService picService;
    @Autowired
    private WorkqualityQueryService workqualityQueryService;
    @Autowired
    private WorkQuaDetailQuery workQuaDetailQuery;
    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;
    @Autowired
    private OrganizationQuery organizationQuery;
    @Autowired
    private IWorkFlowService iworkFlowService;
    @Autowired
    private EnterpriseQuery enterpriseQuery;
    /**
     * 根据项目id查询开工报告
     * @param pkproject
     * @return
     * @throws BusinessException
     */
    @Override
    public WorkStartVO[] getAllCondition(String pkproject) throws BusinessException {
        //根据项目id查询项目对应的开工报告
        WorkStartVO[] workStartVOS = workStartMapper.selectAllCondition(pkproject);
        //获取项目信息
        ProjectVO projectVO= projectSimpleQuery.queryProject(pkproject);
        //填充项目信息
        wrapProjectInfo(workStartVOS, projectVO);
        //获取不合格照片信息
        wrapWorkStartPictures(workStartVOS);

        return workStartVOS;

    }

    /**
     * 封装项目信息
     * @param workStartVOS
     * @param projectVO
     * @throws BusinessException
     */
    private void wrapProjectInfo(WorkStartVO[] workStartVOS, ProjectVO projectVO) throws BusinessException {
        for (WorkStartVO workstart : workStartVOS) {
            //赋值项目名以及项目编号
            workstart.setProjectName(projectVO.getSname());
            workstart.setProjectCode(projectVO.getScode());
            //获取条件主键
            String pkWorkquality = workstart.getPkWorkquality();
            //获取开工条件对象
            WorkqualityVO workqualityVO=  workqualityQueryService.queryByID(pkWorkquality);
            //赋值条件名
            workstart.setConditionName(workqualityVO.getCheckname());
        }
    }

    /**
     * 为不合格的检查项添加照片 最多支持9张
     * @param workStartVOs
     * @throws BusinessException
     */
    private void wrapWorkStartPictures(WorkStartVO[] workStartVOs) throws BusinessException {
        if(workStartVOs == null || workStartVOs.length == 0) {
            return ;
        }
        //开工报告主键集合
        List<String> pkBills = Arrays.stream(workStartVOs).filter(workStartVO -> workStartVO != null && StringUtils.isNotEmpty(workStartVO.getPkWorkstartreport()) )
                .map(workStartVO -> workStartVO.getPkWorkstartreport()).collect(Collectors.toList());

        //查询出所有单据下的检查项
        WorkStartCheckVO[] workStartCheckVOS = checkMapper.selectByBills(SqlUtil.getSqlIn(pkBills.toArray(new String[pkBills.size()])));
        if (ArrayUtils.isEmpty(workStartCheckVOS)) {
            return;
        }
        //不合格的检查项主键以及对应的单据主键
        Map<String, String> nopassCheckItemMap = Arrays.stream(workStartCheckVOS).filter(workStartCheckVO -> workStartCheckVO.getQualification() == InspectItemBillStatusConst.BILLSTATUS_NO_PASS)
                .collect(Collectors.toMap(WorkStartCheckVO::getPkCheck, WorkStartCheckVO::getPkWorkstartreport, (v1, v2) -> v1));
        if(nopassCheckItemMap == null || nopassCheckItemMap.size() == 0){
            return;
        }
        //根据检查项ID查寻检查项对应的是图片名称的集合
        Map<String, List<String>> picMap = picService.queryPicsByPkEntitys(nopassCheckItemMap.keySet().toArray(new String[pkBills.size()]));
        if (picMap.size() == 0) return;
        //该集合key对应单据ID，value对应的图片名称集合，最多只允许展示九张照片
        Map<String, List<String>> parentPicMap = new HashMap<>();
        //获取开工报告对应的图片名称
        getPicMap(nopassCheckItemMap, picMap, parentPicMap);
        //为单据展示对象的pictures属性赋值
        Arrays.stream(workStartVOs).forEach(
                workStartVO -> workStartVO.setPictures(parentPicMap.get(workStartVO.getPkWorkstartreport()) != null ? parentPicMap.get(workStartVO.getPkWorkstartreport()).toArray(new String[]{}) : new String[]{})
        );
    }

    /**
     * 获取开工报告对应的图片名称
     * @param nopassCheckItemMap
     * @param picMap
     * @param parentPicMap
     */
    private void getPicMap(Map<String, String> nopassCheckItemMap, Map<String, List<String>> picMap, Map<String, List<String>> parentPicMap) {
        //根据key遍历Map集合
        for (String key : picMap.keySet()) {
            //检查项主键对应的单据(开工报告)主键
            String pkParent = nopassCheckItemMap.get(key);
            if(pkParent == null) continue ;
            if (parentPicMap.get(pkParent) == null) {
                parentPicMap.put(pkParent, new ArrayList<String>());
            }
            //最多取9张照片
            if (parentPicMap.get(pkParent).size() < 9) {
                int need = 9 - parentPicMap.get(pkParent).size();
                for (int i = 0; i < Math.min(need, picMap.get(key).size()); i++) {
                    parentPicMap.get(pkParent).add(picMap.get(key).get(i));
                }
            }

        }
    }

    /**
     * 根据开工报告查询开工报告信息
     * @param reportId
     * @return
     * @throws BusinessException
     */
    @Override
    public WorkStartVO getReport(String reportId) throws BusinessException {
        //根据单据ID查询出单据信息
        WorkStartVO workStartVO = workStartMapper.selectReport(reportId);

        //根据条件主键与开工报告查询检查项   条件主键多余
        WorkStartCheckVO[] workStartCheckVOS = checkMapper.selectAllCheck(workStartVO.getPkWorkquality(), reportId);
        WorkqualityVO workqualityVO = workqualityQueryService.queryByID(workStartVO.getPkWorkquality());
        //封装检查项信息
        wrapWorkstartCheckVo(workStartVO,workStartCheckVOS,workqualityVO);
        //封装开工报告信息
        wrapWorkStartInfo(workStartVO,workqualityVO);

        return workStartVO;

    }

    /**
     * 封装开工报告信息
     * @param workStartVO
     */
    private void wrapWorkStartInfo(WorkStartVO workStartVO,WorkqualityVO workqualityVO) throws BusinessException {
        //填充单据状态名称
        wrapBillStatus(workStartVO);
        //获取开工条件对象

        if(workqualityVO != null){
            workStartVO.setConditionName(workqualityVO.getCheckname());
        }

        //根据项目Id获取项目名以及项目编号
        String pkProject = workStartVO.getPkProject();
        ProjectVO projectVO= projectSimpleQuery.queryProject(pkProject);
        if(projectVO == null){
            return;
        }
        workStartVO.setCanApprove(false);
        boolean b = iworkFlowService.checkApprovePerm(workStartVO.getPkWorkstartreport(), RuntimeEnvironment.getLoginUserId());
        if(b){
            workStartVO.setCanApprove(true);
        }
        String pkEnterprise = workStartVO.getPkEnterprise();
        String pkSupervision = workStartVO.getPkSupervision();
        if(StringUtils.isNotBlank(pkEnterprise) || StringUtils.isNotBlank(pkSupervision) ){
            List<String> enterprises = new ArrayList<String>();
            if(StringUtils.isNotBlank(pkEnterprise)){
                enterprises.add(pkEnterprise);
            }
            if(StringUtils.isNotBlank(pkSupervision)){
                enterprises.add(pkSupervision);
            }
            EnterpriseVO[] enterpriseVOS = enterpriseQuery.queryByIds(enterprises.toArray(new String[0]));
            Map<String, String> collect = Arrays.stream(enterpriseVOS).filter(vo -> StringUtils.isNotEmpty(vo.getName())).collect(Collectors.toMap(EnterpriseVO::getPkEnterprise, EnterpriseVO::getName));
            workStartVO.setSupervisionName(collect.get(pkSupervision));
            workStartVO.setEnterpriseName(collect.get(pkEnterprise));
        }
        workStartVO.setProjectName(projectVO.getSname());
        workStartVO.setProjectCode(projectVO.getScode());
        if(StringUtils.isEmpty(projectVO.getPkOrg())){
            return ;
        }
        OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), projectVO.getPkOrg());
        if(organizationVO == null){
          return ;
        }
        workStartVO.setOrgName(organizationVO.getSname());
        workStartVO.setPkOrganization(organizationVO.getPkOrganization());
        workStartVO.setPkOrgSrc(organizationVO.getPkSrc());


    }

    /**
     * 封装检查项信息
     *
     * @param workStartVO
     * @param workStartCheckVOS
     * @param workqualityVO
     * @throws BusinessException
     */
    private void wrapWorkstartCheckVo(WorkStartVO workStartVO, WorkStartCheckVO[] workStartCheckVOS, WorkqualityVO workqualityVO) throws BusinessException {
        if(workStartCheckVOS == null || workStartCheckVOS.length == 0){
            return;
        }
        List<String> checkItems = Arrays.stream(workStartCheckVOS).map(WorkStartCheckVO::getPkWorkqualitydetail).collect(Collectors.toList());
        WorkqualityDetailVO[] workqualityDetailVOS = workqualityVO.getItemtabledata();
        Map<String, WorkqualityDetailVO> workqualityDetailMap = Arrays.stream(workqualityDetailVOS).collect(Collectors.toMap(WorkqualityDetailVO::getPkWorkqualitydetail, WorkqualityDetailVO -> WorkqualityDetailVO));
        //遍历补全检查项信息
        for (int i = 0; i < workStartCheckVOS.length; i++) {
            WorkStartCheckVO workStartCheckVO = workStartCheckVOS[i];
            String pkWorkqualitydetail = workStartCheckVO.getPkWorkqualitydetail();
            WorkqualityDetailVO workqualityDetailVO = workqualityDetailMap.get(pkWorkqualitydetail);
            if(workqualityDetailVO != null){
                workStartCheckVO.setCheckName(workqualityDetailVO.getCheckitem());
                workStartCheckVO.setDescription(workqualityDetailVO.getCheckdescription());
                workStartCheckVO.setNeedPhoto(workqualityDetailVO.getNeedphoto());
                if(workqualityDetailVO.getExamplePictures() !=null && workqualityDetailVO.getExamplePictures().length > 0){
                    workStartCheckVO.setExamplesPictures(workqualityDetailVO.getExamplePictures());
                }

            }

            //查询图片 打印模板时会用到
            if (workStartCheckVOS[i].getLogo() == CheckItemConst.LOGO_ALL_PROSSESS) {
                String[] pictures = picService.queryPicNamesByPkEntity(workStartCheckVOS[i].getPkCheck());
                workStartCheckVOS[i].setPictures(pictures);
            }


            if(workStartCheckVOS[i].getQualification() != null ) {
                //是否具备资格
                switch (workStartCheckVOS[i].getQualification()) {
                    case CheckItemConst.QUALIFICATION_HAVE:
                        workStartCheckVOS[i].setQualificationName(CheckItemConst.QUALIFICATION_HAVE_NAME);
                        break;
                    case CheckItemConst.QUALIFICATION_NO_HAVE:
                        workStartCheckVOS[i].setQualificationName(CheckItemConst.QUALIFICATION_NO_HAVE_NAME);
                        break;
                    case CheckItemConst.QUALIFICATION_NO_APPLICABLE:
                        workStartCheckVOS[i].setQualificationName(CheckItemConst.QUALIFICATION_NO_APPLICABLE_NAME);
                }
            }

        }

        workStartVO.setWorkStartCheckVOS(workStartCheckVOS);
    }

    private void wrapBillStatus(WorkStartVO workStartVO) {
        //判断单据状态
        if (workStartVO.getBillstatus() != null) {
            switch (workStartVO.getBillstatus()) {
                case BillStatusConst.COMMON_APPROVING_STATUS:
                    workStartVO.setStatus(BillStatusConst.COMMON_APPROVING_STATUS_NAME);
                    break;
                case BillStatusConst.COMMON_REJECT_STATUS:
                    workStartVO.setStatus(BillStatusConst.COMMON_REJECT_STATUS_NAME);
                    break;
                case BillStatusConst.COMMON_APPROVED_STATUS:
                    workStartVO.setStatus(BillStatusConst.COMMON_APPROVED_STATUS_NAME);
                    break;
                case BillStatusConst.COMMON_COMMIT_STATUS:
                    workStartVO.setStatus(BillStatusConst.COMMON_COMMIT_STATUS_NAME);
                    break;
                case BillStatusConst.COMMON_FREE_STATUS:
                    workStartVO.setStatus(BillStatusConst.COMMON_FREE_STATUS_NAME);
            }
        }
    }


    /**
     * 根据检查项id获取检查项信息
     * @param checkId
     * @return
     * @throws BusinessException
     */
    @Override
    public WorkStartCheckVO getCheck(String checkId) throws BusinessException {
        WorkStartCheckVO workStartCheckVO = checkMapper.selectCheck(checkId);
        //获取检查项的名称
        WorkqualityDetailVO byId = workQuaDetailQuery.getById(workStartCheckVO.getPkWorkqualitydetail());
//        String s = workStartMapper.selectName(byId.getCheckitem());
        workStartCheckVO.setCheckName(byId.getCheckitem());
        //查询检查项ID对应的图片
        String[] pictures = picService.queryPicNamesByPkEntity(workStartCheckVO.getPkCheck());
        workStartCheckVO.setPictures(pictures);
        return workStartCheckVO;

    }


    /**
     * 根据条件查询开工报告
     * @param billViewQueryVO
     * @return
     * @throws BusinessException
     */
    @Override
    public PageObject<Object> queryByCondition(BillViewQueryVO billViewQueryVO) throws BusinessException {
        JSONObject extendsParams =billViewQueryVO.getExtendsParams();
        String[] pkEnterprises =  extendsParams != null && StringUtils.isNotBlank(extendsParams.getString("pkEnterprises"))? extendsParams.getString("pkEnterprises").split(","): null ;
        String[] pkorgs = extendsParams != null && StringUtils.isNotBlank(extendsParams.getString("pkorgs"))?extendsParams.getString("pkorgs").split(","): null ;
        String pkOrg = billViewQueryVO.getPkOrg();
        String[] pkProject = billViewQueryVO.getPkProject();
        int start = billViewQueryVO.getPageStart();
        String startDate = billViewQueryVO.getStartTime();
        String endDate = billViewQueryVO.getEndTime();
        int[] billStatus = billViewQueryVO.getBillStatus();
        String[] creators = billViewQueryVO.getCreators();
        int size = billViewQueryVO.getPageSize();
        String tenantId = RuntimeEnvironment.getTenantId();
        //根据条件查询开工报告总数量
        int count = workStartMapper.countByCondition(pkProject, pkorgs, pkEnterprises, tenantId,creators, startDate, endDate, billStatus);
        //查询符合条件的开工报告
        WorkStartVO[] workStartVOS = workStartMapper.queryByCondition(pkProject, pkorgs, pkEnterprises, tenantId, creators, startDate, endDate, billStatus, start, size);

        if(workStartVOS == null || workStartVOS.length ==0){
            return new PageObject<Object>(workStartVOS, count, start);
        }

        return new PageObject<Object>(workStartVOS, count, start);
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException{

        int count = workStartMapper.countByCondition( new String[]{param.getPkProject()}, null,null,null, null,  param.getStartDate(), param.getEndDate(), null);

        return count;
    }

    @Override
    public WorkStartVO[] queryByProject(QueryListParam param) throws BusinessException {
        WorkStartVO[] vos = workStartMapper.queryByCondition(new String[]{param.getPkProject()}, null,null, null,null,  param.getStartDate(), param.getEndDate(), null,param.getPageStart(),param.getPageSize());
        wrapWorkStartPictures(vos);
        return vos;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.WORKSTART_BILLTYPE;
    }
}